<template>
  <div class="app-container">
    <el-card class="tableset" shadow="never" :body-style="{ padding: '0px' }">
      <!-- 小标题 -->
      <div class="title">
        <span>错误代码速查</span>
        <el-button
          v-permission="['error-code-add']"
          type="primary"
          class="title-button-right"
          icon="el-icon-plus"
          style="margin-left: 0.5rem;"
          plain
          @click="openAddErrorCodeDialog"
        >新增错误代码信息</el-button>
      </div>
      <!-- 小标题 -->

      <!-- 搜索关键词 -->
      <div class="funtion">
        <el-select
          v-model="get_error_code_info_list.printer_id"
          style="width: 180px"
          placeholder="请选择打印机品牌及型号"
          @change="getErrorCodeInfoList"
        >
          <el-option
            v-for="item in data_error_code_info_list.printer"
            :key="item.printer_id"
            :label="item.brand + item.model_number"
            :value="item.printer_id"
          >
            <span style="float: left;margin-right: 0.5rem;">{{ item.brand }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.model_number }}</span>
          </el-option>
        </el-select>
        <el-input
          v-model="get_error_code_info_list.keywordErrorCode"
          placeholder="请输入错误代码"
          class="input-with-select input"
          clearable
          @keyup.enter.native="getErrorCodeInfoList"
        >
          <el-select
            slot="prepend"
            v-model="get_error_code_info_list.keywordType"
            placeholder="请选择"
            class="option"
          >
            <el-option label="错误代码" value="0" />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="getErrorCodeInfoList" />
        </el-input>
      </div>
      <!-- 搜索关键词 -->

      <!-- 数据表 -->
      <el-table
        v-loading="dataRequestLoading"
        element-loading-text="正在加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        class="table"
        :data="data_error_code_info_list.data"
        highlight-current-row
        stripe
        style="width: 100%;"
        :height="tableHeight"
        :max-height="tableHeight"
        @selection-change="getSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="printer_id" label="打印机品牌及型号">
          <template slot-scope="{ row }">
            <span>{{ printer_id_brand_model_number(row.printer_id) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="error_code" label="错误代码" />
        <el-table-column prop="create_time" label="创建时间" />
        <el-table-column label="操作" width="160px">
          <template slot-scope="{ row }">
            <el-button v-permission="['error-code-view']" type="success" @click.stop="openCheckErrorCodeDialog(row)">查看</el-button>
            <el-button v-permission="['error-code-change']" type="primary" @click.stop="openEditErrorCodeDialog(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据表 -->

      <!-- 数据表左下方功能区 -->
      <div>
        <el-button
          v-permission="['error-code-delete']"
          type="danger"
          class="card-bottom-button-left"
          icon="el-icon-delete"
          style="margin-left: 0.5rem;"
          plain
          :disabled="deleteDisabled"
          @click="deleteErrorCodeInfo"
        >删除</el-button>
      </div>
      <!-- 数据表左下方功能区 -->

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="total, sizes,prev, pager, next, jumper"
        :total="data_error_code_info_list.total"
        :page-size="get_error_code_info_list.pageSize"
        :page-sizes="[20, 50, 100]"
        :current-page="get_error_code_info_list.currentPage"
        @size-change="changePageSize"
        @current-change="changeCurrentPage"
      />
      <!-- 分页 -->
    </el-card>

    <!-- 新增/修改错误代码信息dialog -->
    <el-dialog
      :title="changeErrorCodeDialogTitle"
      :visible.sync="changeErrorCodeDialog"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="changeErrorCodeRulesForm"
        :model="change_error_code_info"
        status-icon
        size="mini"
        label-width="90px"
      >
        <el-form-item prop="printer_id" :rules="rules.select" label="打印机品牌及型号">
          <el-select v-model="change_error_code_info.printer_id" placeholder="请选择">
            <el-option
              v-for="item in data_error_code_info_list.printer"
              :key="item.printer_id"
              :label="item.brand + item.model_number"
              :value="item.printer_id"
            >
              <span style="float: left;margin-right: 0.5rem;">{{ item.brand }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.model_number }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="error_code" :rules="rules.input" label="错误代码">
          <el-input v-model="change_error_code_info.error_code" placeholder="请输入错误代码" clearable />
        </el-form-item>
        <el-form-item prop="reason" :rules="rules.input" label="错误原因">
          <el-input v-model="change_error_code_info.reason" type="textarea" :autosize="{ minRows: 4, maxRows: 4}" placeholder="请输入错误原因" clearable />
        </el-form-item>
        <el-form-item prop="handing_method" :rules="rules.input" label="处理方法描述文字">
          <el-input v-model="change_error_code_info.handing_method" type="textarea" :autosize="{ minRows: 5, maxRows: 5}" placeholder="请输入处理方法描述文字" clearable />
        </el-form-item>
        <el-form-item label="上传图片描述">
          <el-upload
            action
            :auto-upload="false"
            list-type="picture-card"
            :file-list="change_error_code_info.show_path"
            :show-file-list="true"
            :limit="8"
            :on-change="changeUploadImage"
            :on-exceed="checkNumber"
            :on-preview="handlePictureCardPreviewImage"
            :on-remove="handleRemoveImage"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeErrorCodeDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeErrorCodeInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增/修改错误代码信息dialog -->

    <!-- 查看错误代码信息dialog -->
    <el-dialog
      title="查看错误代码信息"
      :visible.sync="checkErrorCodeDialog"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-form size="mini" label-width="130px">
        <el-divider content-position="left">基础</el-divider>
        <el-form-item label="打印机品牌及型号">
          <span>{{ change_error_code_info.printer_id }}</span>
        </el-form-item>
        <el-form-item label="错误代码">
          <span>{{ change_error_code_info.error_code }}</span>
        </el-form-item>
        <el-divider content-position="left">错误原因</el-divider>
        <el-form-item>
          <div v-html="change_error_code_info.reason" />
        </el-form-item>
        <el-divider content-position="left">处理方法描述文字</el-divider>
        <el-form-item>
          <div v-html="change_error_code_info.handing_method" />
        </el-form-item>
        <div
          v-for="(item, index) in change_error_code_info.show_path"
          :key="index"
          style="text-align: center;"
        >
          <img :src="item.url" width="665" height="665">
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看错误代码信息dialog -->

    <!-- 查看图片dialog -->
    <el-dialog :visible.sync="imageDialog" custom-class="full-dialog">
      <img width="100%" :src="dialogImageUrl" alt>
    </el-dialog>
    <!-- 查看图片dialog -->

    <!-- 剪切图片dialog -->
    <el-dialog title="图片剪裁" :visible.sync="UploadImagerDialog" :close-on-click-modal="false">
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :info="option.info"
            :output-size="option.size"
            :output-type="option.outputType"
            :can-scale="option.canScale"
            :auto-crop="option.autoCrop"
            :auto-crop-width="option.autoCropWidth"
            :auto-crop-height="option.autoCropHeight"
            :fixed-box="option.fixedBox"
            :fixed="option.fixed"
            :fixed-number="option.fixedNumber"
            :full="option.full"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :center-box="option.centerBox"
            :info-true="option.infoTrue"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="UploadImagerDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="uploadLoading" @click="upLoadImage">确认</el-button>
      </div>
    </el-dialog>
    <!-- 剪切图片dialog -->
  </div>
</template>

<script>
import { getFormData } from '@/common/js/until'
import { uploadImage } from '@/api/upload'
import { getErrorCodeInfoList, changeErrorCodeInfo, deleteErrorCodeInfo } from '@/api/error-code'
export default {
  data() {
    return {
      // table高度自适应
      tableHeight: window.innerHeight - 265,

      // loading开关
      dataRequestLoading: false,

      // 按钮开关
      deleteDisabled: true,

      // loading开关
      uploadLoading: false,

      // dialog开关
      changeErrorCodeDialog: false,
      UploadImagerDialog: false,
      checkErrorCodeDialog: false,

      // 展示图片
      imageDialog: false,
      dialogImageUrl: false,

      // 图片裁剪框
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 665, // 默认生成截图框宽度
        autoCropHeight: 665, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [1, 1], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },

      // dialog标题
      changeErrorCodeDialogTitle: '',

      // 发送请求参数
      get_error_code_info_list: {
        pageSize: 20,
        currentPage: 1,
        keywordErrorCode: '',
        keywordType: '0',
        sort_name: '',
        sort: 'desc',
        printer_id: ''
      },

      // 返回值
      data_error_code_info_list: {
        data: [],
        printer: [],
        total: 0
      },

      // 新增/修改参数
      change_error_code_info: {
        error_code_id: '',
        printer_id: '',
        error_code: '',
        reason: '',
        handing_method: '',
        path: [],
        show_path: []
      },

      // 表单校验规则
      rules: {
        input: { required: true, message: '请完成输入！', trigger: 'blur' },
        select: { required: true, message: '请完成选择！', trigger: 'blur' }
      }
    }
  },
  mounted() {
    this.getErrorCodeInfoList() // 查询错误代码信息列表
  },
  methods: {
    // 查询错误代码信息列表
    getErrorCodeInfoList() {
      this.dataRequestLoading = true
      getErrorCodeInfoList(this.get_error_code_info_list).then(res => {
        res.result.showing.forEach(val => {
          val.path = JSON.parse(val.path)
        })
        this.data_error_code_info_list.data = res.result.showing
        this.data_error_code_info_list.printer = res.result.printer
        this.data_error_code_info_list.total = res.result.total
        this.dataRequestLoading = false
      })
    },

    // 打印机品牌及型号显示
    printer_id_brand_model_number(data) {
      const printer_id = this.data_error_code_info_list.printer.filter(v => {
        if (v.printer_id === data) {
          return v.brand + v.model_number
        }
      })
      return printer_id[0].brand + printer_id[0].model_number
    },

    // 新增/修改错误代码信息
    changeErrorCodeInfo() {
      this.$refs.changeErrorCodeRulesForm.validate(valid => {
        if (valid) {
          changeErrorCodeInfo(this.change_error_code_info).then(res => {
            this.$notify({
              title: '成功',
              message: '保存成功！',
              type: 'success'
            })
            this.getErrorCodeInfoList()
            this.changeErrorCodeDialog = false
          })
        } else {
          return false
        }
      })
    },
    // 切换每页条数方法
    changePageSize(data) {
      this.get_error_code_info_list.pageSize = data
      this.getErrorCodeInfoList()
    },

    // 切换页码方法
    changeCurrentPage(data) {
      this.get_error_code_info_list.currentPage = data
      this.getErrorCodeInfoList()
    },

    // 获取选择项
    getSelection(selection) {
      if (selection.length === 0) {
        this.deleteDisabled = true
      } else {
        this.deleteDisabled = false
      }
      this.selection = selection
    },

    // 删除错误代码信息（逻辑删除）
    deleteErrorCodeInfo() {
      this.$confirm('此操作将永久删除该错误代码信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const error_code_id = []
        this.selection.forEach(val => {
          error_code_id.push(val.error_code_id)
        })
        deleteErrorCodeInfo({ error_code_id: error_code_id }).then(res => {
          this.$notify({
            title: '成功',
            message: '删除错误代码信息成功！',
            type: 'success'
          })
          this.getErrorCodeInfoList()
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },

    // 查看错误代码信息
    openCheckErrorCodeDialog(row) {
      this.change_error_code_info = {
        error_code_id: row.error_code_id,
        printer_id: this.printer_id_brand_model_number(row.printer_id),
        error_code: row.error_code,
        reason: row.reason.replace(new RegExp('\n', 'g'), '<br/>'),
        handing_method: row.handing_method.replace(new RegExp('\n', 'g'), '<br/>'),
        path: row.path,
        show_path: []
      }
      if (row.path.length > 0) {
        row.path.forEach(val => {
          const image = {
            url: process.env.VUE_APP_BASE_API + val,
            path: val
          }
          this.change_error_code_info.show_path.push(image)
        })
      }
      this.checkErrorCodeDialog = true
    },

    // 新增错误代码信息界面
    openAddErrorCodeDialog() {
      this.changeErrorCodeDialogTitle = '新增错误代码信息'
      this.change_error_code_info = {
        error_code_id: '',
        printer_id: '',
        error_code: '',
        reason: '',
        handing_method: '',
        path: [],
        show_path: []
      }
      this.changeErrorCodeDialog = true
    },

    // 修改错误代码信息界面
    openEditErrorCodeDialog(row) {
      this.changeErrorCodeDialogTitle = '修改错误代码信息'
      this.change_error_code_info = {
        error_code_id: row.error_code_id,
        printer_id: row.printer_id,
        error_code: row.error_code,
        reason: row.reason,
        handing_method: row.handing_method,
        path: row.path,
        show_path: []
      }
      if (row.path.length > 0) {
        row.path.forEach(val => {
          const image = {
            url: process.env.VUE_APP_BASE_API + val,
            path: val
          }
          this.change_error_code_info.show_path.push(image)
        })
      }
      this.changeErrorCodeDialog = true
    },

    // 打开剪切界面
    changeUploadImage(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 2
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        fileList.pop()
        return false
      }
      if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
        this.$message.error('上传图片只支持jpeg和png!')
        fileList.pop()
        return false
      }
      // 将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        fileList.pop()
        this.option.img = URL.createObjectURL(file.raw)
        this.UploadImagerDialog = true
      })
    },
    // 上传剪切后的图片
    upLoadImage() {
      this.$refs.cropper.getCropBlob(data => {
        const formData = getFormData(data, 'error-code')
        uploadImage(formData).then(res => {
          const image = {
            url: process.env.VUE_APP_BASE_API + res.result,
            path: res.result
          }
          this.change_error_code_info.show_path.push(image)
          this.change_error_code_info.path.push(res.result)
          this.UploadImagerDialog = false
        })
      })
    },
    // 检测上传数量
    checkNumber() {
      this.$message({ type: 'warning', message: '只能上传八张图片！' })
    },
    // 查看放大图
    handlePictureCardPreviewImage(file) {
      this.dialogImageUrl = file.url
      this.imageDialog = true
    },
    // 删除对应图片
    handleRemoveImage(file, fileList) {
      const indexPath = this.change_error_code_info.path.indexOf(file.path)
      this.change_error_code_info.path.splice(indexPath, 1)
      const indexShowPath = this.change_error_code_info.show_path.indexOf(file)
      this.change_error_code_info.show_path.splice(indexShowPath, 1)
    }

  }
}
</script>

<style scoped>

</style>
